﻿$(function () {
	var oid =window.sessionStorage.getItem("organizeId");
	$.ajax({
		type:"GET",
		url: $.httpRootPath()+"api/web/department/i/"+oid+"/dep-tree",
		dataType: "json",
		success: function (reply) {
			if(reply.code == 0){
				tree(reply.data);
				listen();
			}else{
				layer.msg('获取数据失败', {icon:0});
				setTimeout(function(){
					history.go(-1);
				},3000);
				
			}
		}
	})
    function tree(data) {
        for (var i = 0; i < data.length; i++) {
            var data2 = data[i];
          
            if (data[i].icon == "icon-th") {
                $("#rootUL").append("<li data-name='" + data[i].id + "'><span><i class='" + data[i].icon + "'></i> " + data[i].name + "</span></li>");
            } else {
                var children = $("li[data-name='" + data[i].parentId + "']").children("ul");
                if (children.length == 0) {
                    $("li[data-name='" + data[i].parentId + "']").append("<ul></ul>")
                }
                $("li[data-name='" + data[i].parentId + "'] > ul").append(
                    "<li data-name='" + data[i].id + "'>" +
                    "<span>" +
                    "<i class='" + data[i].icon + "'></i> " +
                    data[i].name +
                    "</span>" +
                    "</li>")
            }
            for (var j = 0; j < data[i].child.length; j++) {
            	 
                var child = data[i].child[j];
                var children = $("li[data-name='" + child.parentId + "']").children("ul");
                if (children.length == 0) {
                    $("li[data-name='" + child.parentId + "']").append("<ul></ul>")
                }
                $("li[data-name='" + child.parentId + "'] > ul").append(
                    "<li data-name='" + child.id + "'>" +
                    "<span>" +
                    "<i class='" + child.icon + "'></i> " +
                    child.name +
                    "</span>" +
                    "</li>")
                var child2 = data[i].child[j].child;
                tree(child2)
            }
            tree(data[i]);
        }
    }
    function listen() {
				$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', '关闭');
				$('.tree li.parent_li > span').on('click', function(e) {
					var children = $(this).parent('li.parent_li').find(' > ul > li');
					if(children.is(":visible")) {
						children.hide('fast');
						$(this).attr('title', '展开').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');
					} else {
						children.show('fast');
						$(this).attr('title', '关闭').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');
					}
					e.stopPropagation();
				});
	}
 function getQueryString(name) { 
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
	var r = window.location.search.substr(1).match(reg); 
	if (r != null) return unescape(r[2]); return null; 
} 

});